#include "gaia_common.h"
#include "gaia_db.h"

/**************************************
 * 函数名：gaia_task
 * 函数功能：对远处主机执行操作
 * 返回值：成功 0,失败　1
 **************************************/

int gaia_task(char *uri_buf)
{
  int i,j;
  MYSQL_RES *res;
  MYSQL_ROW  row; 

  /* 返回json格式的字符串 */
  char *callback_str_suc_tmp = "{\"hostid\":%d,\"status\":success}";
  char *callback_str_err_tmp = "{\"hostid\":%d,\"status\":fail}";

  char *tmp_sql = "select username,passwd,host,port from gaia_host_info where hostid=%d";
  char sql[128];

  /* 存放执行过程 */
  char exec_result[1024];
  memset(exec_result,'\0',1024);

 /* 存放post数据信息 */
  HOST *hostinfo;
  hostinfo = (HOST *)malloc(sizeof(HOST));
  
  if(NULL == hostinfo)
  {
    fprintf(stderr,"hostinfo malloc error!\n");
    return 1;
  }

  /* 解析Post过来的数据 */
  gaia_parse_post_data(1,uri_buf,&hostinfo);
//printf("hostinfo->hostid = %d\n",hostinfo->hostid);

  sprintf(sql,tmp_sql,hostinfo->hostid);
  printf("%s\n",sql);
  /* 根据hostid查询主机的信息,如用户名、密码、IP等 */
  if( (res = gaia_db_vselect(sql)) == NULL)
  {
    fprintf(stderr,"select hostinfo error!\n");
    return 1;
  }


  row = mysql_fetch_row(res);
  /*
  j = mysql_num_fields(res);
  while( (row = mysql_fetch_row(res)) )
  {
    for(i = 0;i < j;i++)
    {
      strncpy(hostinfo[i],row[i],strlen(row[i]));
      printf("%s\n",row[i]);
      printf("hostinfo[%d] = %s\n",i,hostinfo[i]);
    }
  }
  */
  strcpy(hostinfo->username,row[0]);
  strcpy(hostinfo->passwd,row[1]);
  strcpy(hostinfo->host,row[2]);
  hostinfo->port = atoi(row[3]);

  /* exec_result 回显执行过程 */
  int rc = gaia_remote_operation(hostinfo->host,hostinfo->username,
                                 hostinfo->passwd,hostinfo->port,hostinfo->task,
                                 exec_result);
  //int rc = gaia_remote_operation("192.168.10.146","root","shopex",22,"ls",exec_result);

  if(rc != 0)
  {
   /* 错误信息 */
   char *callback_str_err = NULL;
   sprintf(callback_str_err,callback_str_err_tmp,hostinfo->hostid);

   fprintf(stderr,"remote operation fail!\n");
   /* 结果返回到web ui */
   gaia_callback(callback_str_err);
   /* 释放申请的内存 */
   free(hostinfo);
   return 1;
  }

  /* 返回成功信息 */
  char *callback_str_suc = NULL;
  sprintf(callback_str_suc,callback_str_suc_tmp,hostinfo->hostid);
  gaia_callback(callback_str_suc);
  
  free(hostinfo);
  return 0;
}
